﻿using System;
//using System.Collections.Generic;
//using System.Linq;
using System.Reflection;
//using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
//using System.IO;
namespace TE3
{
	public static class Script
	{
		public static string Compile(string source, string scriptName)
		{
			var provider = new CSharpCodeProvider();
			var scriptNameNE = scriptName.Remove(scriptName.Length - 3, 3);
			var parameters = new CompilerParameters(new[] { "TE3Script.dll", "TE3.dll", "Microsoft.Xna.Framework.Game.dll" }, scriptName)
			{
				OutputAssembly = Environment.CurrentDirectory + "/Scripts/bin/" + scriptNameNE + ".dll",
				WarningLevel = 3
			};
			var results = provider.CompileAssemblyFromSource(parameters, new[] {source});
			if(results.Errors.Count < 1)
				Console.WriteLine("Script compiled: " + scriptName);
			else
			{
				foreach (var error in results.Errors)
				{
					Console.WriteLine(error);
				}
			}
			return scriptNameNE;
		}
		public static void Execute(string fileName,TE3Game game = null)
		{
			Assembly asm;
			try
			{
				asm = Assembly.LoadFrom(Environment.CurrentDirectory + "/Scripts/bin/" + fileName + ".dll");
			}
			catch (Exception ex)
			{
				Console.WriteLine("Error loading script:" + fileName);
				Console.WriteLine(ex.Message+"\n"+ex.InnerException);
				return;
			}
			Type type = null;
			try
			{
				type = asm.GetType(fileName + ".Main");
			}
			catch(Exception ex)
			{
				Console.WriteLine("Main class not found in " + fileName);
				Console.WriteLine(ex.Message);
				return;
			}
			var script = (IScript)Activator.CreateInstance(type);
			type.InvokeMember("Init", BindingFlags.InvokeMethod, null, script, new[] {game});
		}
	}
}
